package com.site.blog.my.core.controller.admin;

import com.site.blog.my.core.constant.TbSystemConstant;
import com.site.blog.my.core.entity.FileInfo;
import com.site.blog.my.core.service.ConfigService;
import com.site.blog.my.core.service.FileInfoService;
import com.site.blog.my.core.util.FileUtil;
import com.site.blog.my.core.util.PageQueryUtil;
import com.site.blog.my.core.util.Result;
import com.site.blog.my.core.util.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 13
 * @qq交流群 796794009
 * @email 2449207463@qq.com
 * @link http://13blog.site
 */
@Controller
@RequestMapping("/admin")
public class FileInfoController {
    @Resource
    private FileInfoService fileInfoService;
    @Resource
    private ConfigService configService;

    @GetMapping("/files")
    public String filePage(HttpServletRequest request) {
        request.setAttribute("configurations", configService.getAllConfigs(TbSystemConstant.SYSTEM_CONFIG_TYPE));
        request.setAttribute("path", "files");
        return "admin/file";
    }

    @RequestMapping(value = "/files/list", method = RequestMethod.GET)
    @ResponseBody
    public Result list(@RequestParam Map<String, Object> params) {
        if (StringUtils.isEmpty(params.get("page")) || StringUtils.isEmpty(params.get("limit"))) {
            return ResultGenerator.genFailResult("参数异常！");
        }

        PageQueryUtil pageUtil = new PageQueryUtil(params);
        return ResultGenerator.genSuccessResult(fileInfoService.getFileInfoPage(pageUtil));
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/files/delete", method = RequestMethod.POST)
    @ResponseBody
    public Result delete(@RequestBody Integer[] ids) {
        if (ids.length < 1) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        if (fileInfoService.deleteBatch(ids)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("删除失败");
        }
    }

    @PostMapping({"/files/upload"})
    @ResponseBody
    public Result<FileInfo> upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file) throws Exception {
        FileInfo fileInfo = FileUtil.saveUploadFile(file, true);

        return ResultGenerator.genSuccessResult().setData(fileInfo);
    }


}
